import { TCpId } from "@/models/types";
import { computed, ref, Ref } from "vue";
import { IDataSource } from "./types";
import { iterFilterExpr } from "./utils";
import { TComponentServices } from "@/services/componentServices";



export function create(name: string, services: {
    component: TComponentServices
}): IDataSource {
    const cp2FilterMap = new Map<TCpId, Ref<string>>()

    function toSqlWithFilters(requestorId: string): Ref<string> {
        const sql = `select * from ${name}`

        return computed(() => {
            const filters = Array.from(iterFilterExpr(cp2FilterMap, requestorId, [], services.component))
            const whereExpr = filters.map(v => v.value).join(' and ')

            if (whereExpr) {
                return `${sql} where ${whereExpr}`
            }

            return sql
        })
    }


    function addFilter(cpid: TCpId, expression: string): void {
        cp2FilterMap.get(cpid)!.value = expression
    }

    function removeFilters(cpid: TCpId): void {
        cp2FilterMap.get(cpid)!.value = ''
    }

    function initFilter(cpid: TCpId) {
        cp2FilterMap.set(cpid, ref(''))
    }

    return {
        typeName: 'dataSource',
        name,
        toSqlWithFilters,
        addFilter,
        removeFilters,
        initFilter,
    }

}